package com.example.testrecorder;


import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.testrecorder.utils.BitmapUtil;
import com.example.testrecorder.utils.CallSystemCameraOrAlbum;
import com.example.testrecorder.utils.LogUtil;
import com.example.testrecorder.utils.PermissionUtil;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;

public class PersonalDataActivity extends BaseActivity {
    private FrameLayout container;//碎片的容器
    FragmentManager fragmentManager;
    private File imgFile;
    public String imgPathStr="";
    private static final String TAG = "PersonalDataActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_data);
        initView();
        LogUtil.logE(TAG,"create方法执行了……");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtil.logE(TAG,"restart方法执行了……");
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.logE(TAG,"start方法执行了……");
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.logE(TAG,"resume方法执行了……");
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtil.logE(TAG,"pause方法执行了……");
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtil.logE(TAG,"stop方法执行了……");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.logE(TAG,"destroy方法执行了……");
    }

    private void initView() {
        container=findViewById(R.id.container);
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        ViewPerDataFragment viewPerDataFragment = new ViewPerDataFragment();
        fragmentTransaction.replace(R.id.container,viewPerDataFragment);
        fragmentTransaction.addToBackStack(null);//传入一个参数用于描述返回栈的状态，一般传入null
        fragmentTransaction.commit();//提交事务
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode== PermissionUtil.WRITE_AND_READ){
            if(grantResults.length==1&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                FragmentManager supportFragmentManager = getSupportFragmentManager();
                Fragment fragment = supportFragmentManager.findFragmentById(R.id.container);
                if(fragment instanceof ViewPerDataFragment){
                    ViewPerDataFragment viewPerDataFragment= (ViewPerDataFragment) fragment;
                    viewPerDataFragment.cv.setImageBitmap(viewPerDataFragment.bitmapFromPath);
                }else if(fragment instanceof EditPerDataFragment){
                    EditPerDataFragment editPerDataFragment= (EditPerDataFragment) fragment;
                    editPerDataFragment.cv.setImageBitmap(editPerDataFragment.bitmapFromPath);
                }
            }else {
                Toast.makeText(this, "您尚未授予读写SD卡文件的权限，无法展示头像！", Toast.LENGTH_SHORT).show();
            }
        }else if(requestCode==PermissionUtil.RWC){
            if(grantResults.length==2&&grantResults[0]==PackageManager.PERMISSION_GRANTED&&grantResults[1]==PackageManager.PERMISSION_GRANTED){
                FragmentManager supportFragmentManager = getSupportFragmentManager();
                Fragment fragment = supportFragmentManager.findFragmentById(R.id.container);
                if(fragment instanceof EditPerDataFragment){
                    EditPerDataFragment editPerDataFragment= (EditPerDataFragment) fragment;
                    editPerDataFragment.cv.setImageBitmap(editPerDataFragment.bitmapFromPath);
                }
            }else {
                Toast.makeText(this, "您尚未授予读写SD卡文件权限、打开相机权限，无法拍摄头像和保存头像！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CallSystemCameraOrAlbum.CAMERA_REQUEST_CODE){
            FragmentManager supportFragmentManager = getSupportFragmentManager();
            Fragment fragment = supportFragmentManager.findFragmentById(R.id.container);
            EditPerDataFragment editPerDataFragment=null;
            if(fragment instanceof EditPerDataFragment){
                editPerDataFragment= (EditPerDataFragment) fragment;
                imgFile=editPerDataFragment.imgFile;
            }

            if(imgFile.exists()){
                editPerDataFragment.cv.setImageBitmap(BitmapUtil.getBitmapFromPath( editPerDataFragment.imgFile.getAbsolutePath()));
                imgPathStr=imgFile.getAbsolutePath();//给照片的路径变量赋值，以便将该路径保存到SQLite数据库
                LogUtil.logD(TAG,"图片的路径是："+imgFile.getAbsolutePath());
                Bitmap bitmapFromPath = BitmapUtil.getBitmapFromPath(imgPathStr);
            }else{
                Toast.makeText(PersonalDataActivity.this,"您尚未完成拍照。",Toast.LENGTH_SHORT).show();
            }
        }else if(requestCode==PermissionUtil.RWC){
            if(resultCode==RESULT_OK){
                if(Build.VERSION.SDK_INT>=19){
                    handleImageOnKitKat(data);// 4.4 及以上系统使用这个方法处理图片
                }else {
                    handleImageBeforeKitKat(data);// 4.4 以下系统使用这个方法处理图片
                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是 document 类型的 Uri ，则通过 document id 处理
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的 id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.
                    getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 content 类型的 Uri ，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 file 类型的 Uri ，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); // 根据图片路径显示图片
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过 Uri 和 和 selection 来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.
                        Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            imgPathStr=imagePath;
            FragmentManager supportFragmentManager = getSupportFragmentManager();
            Fragment fragmentById = supportFragmentManager.findFragmentById(R.id.container);
            CircleImageView cv=null;
            if(fragmentById instanceof EditPerDataFragment){
                EditPerDataFragment editPerDataFragment= (EditPerDataFragment) fragmentById;
                cv=editPerDataFragment.cv;
            }
            if(cv!=null){
                cv.setImageBitmap(bitmap);
            }
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }
}